// app/SceneListPage.tsx

import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, StyleSheet, FlatList, Image, ActivityIndicator, Alert, Button, TouchableOpacity } from 'react-native';
import { Stack, useFocusEffect, useRouter } from 'expo-router'; // 添加 useRouter
import { FontAwesome } from '@expo/vector-icons';

import 'react-native-gesture-handler';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
// 导入我们需要的组件
import ParallaxScrollView from '../../components/ParallaxScrollView';
import Scene from '../../components/features/device/Scene'; // 导入你朋友写的、带滑动功能的场景组件

// 导入 API 函数和类型
import { createScene, getScenes, adjustScenePriority, deleteScene, ScenePriorityData, updateScene, UpdateSceneData, Scene as ApiSceneType } from '../../api/scene'; // 导入 deleteScene

export default function SceneListPage() {
  const [scenes, setScenes] = useState<ApiSceneType[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter(); // 添加路由钩子

  // 异步获取场景列表的函数
  const fetchScenes = useCallback(async () => {
    // setLoading(true);
    setError(null);
    try {
      // 调用 getScenes API获取数据 
      const response = await getScenes();
      // API文档指出 /scenes/all 返回的 data 对象中包含 scenes 数组 
      setScenes(response.data.data.scenes);
    } catch (err: any) {
      console.error('Failed to fetch scenes:', err.response?.data || err.message);
      setError('无法加载场景列表，请稍后再试。');
      Alert.alert('错误', `无法加载场景列表: ${err.response?.data?.error?.message || err.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  }, []);

  // 组件加载时调用一次获取场景列表
  useEffect(() => {
    fetchScenes();
  }, [fetchScenes]); // 依赖 fetchScenes，确保它不会在每次渲染时重新创建

  useFocusEffect(
    React.useCallback(() => {
      fetchScenes();
    }, [])
  );

  // 调整优先级的逻辑，现在会调用后端 API
  const handlePriorityChange = useCallback(
    async (id: number, direction: 'increase' | 'decrease') => {
      const action: ScenePriorityData['action'] =
        direction === 'increase' ? 'move_up' : 'move_down'; // 将 'increase'/'decrease' 映射到后端API的 'move_up'/'move_down'

      // 乐观更新 UI：先更新本地状态，提高用户体验
      setScenes(currentScenes => {
        const index = currentScenes.findIndex(s => s.id === id);
        if (index === -1) return currentScenes; // 场景未找到

        const newScenes = [...currentScenes];
        if (direction === 'increase' && index > 0) {
          // 和前一个交换位置
          [newScenes[index], newScenes[index - 1]] = [
            newScenes[index - 1],
            newScenes[index],
          ];
        } else if (direction === 'decrease' && index < currentScenes.length - 1) {
          // 和后一个交换位置
          [newScenes[index], newScenes[index + 1]] = [
            newScenes[index + 1],
            newScenes[index],
          ];
        } else {
          return currentScenes; // 无法移动 (已经在顶部或底部)
        }
        return newScenes;
      });

      try {
        await adjustScenePriority(id, { action });
      } catch (err: any) {
        console.error(`Failed to adjust priority for scene ${id}:`, err.response?.data || err.message);
        // alert(`错误调整场景优先级失败`)
        fetchScenes(); // 如果后端请求失败，回滚 UI 状态或者重新获取数据以同步后端状态
      }
    },
    [fetchScenes]
  );


  // 处理删除场景的逻辑
  const handleDeleteScene = useCallback(async (id: number) => {
    try {
      setLoading(true); // 删除操作也显示加载状态
      await deleteScene(id); // 调用删除API 
      // 成功删除后，从本地状态中移除该场景
      setScenes(currentScenes => currentScenes.filter(scene => scene.id !== id));
      alert('成功删除。');
    } catch (err: any) {
      console.error(`Failed to delete scene ${id}:`, err.response?.data || err.message);
      Alert.alert('错误', `删除场景失败: ${err.response?.data?.error?.message || err.message || '未知错误'}`);
      fetchScenes(); // 删除失败后，重新获取列表以同步状态
    } finally {
      setLoading(false);
    }
  }, [fetchScenes]);

  // 处理编辑场景的逻辑
  const handleEditScene = useCallback((sceneId: number, sceneName: string) => {
    // 方式一：使用 Expo Router 跳转到编辑页面，并传递参数
    router.push({
      pathname: '../EditScene/[id]',
      params: { 
        id: sceneId.toString(),
        sceneId: sceneId.toString(), 
        sceneName: sceneName 
      }
    });

    // 方式二：如果你想跳转到外部链接，可以使用这种方式：
    // import { Linking } from 'react-native';
    // const editUrl = `https://yourapp.com/edit/${sceneId}`;
    // Linking.openURL(editUrl).catch(err => {
    //   console.error('打开链接失败:', err);
    //   Alert.alert('错误', '无法打开编辑页面');
    // });
  }, [router]);

  if (loading) {
    return (
      <View style={styles.centered}>
        <ActivityIndicator size="large" color="#0000ff" />
        <Text>加载场景中...</Text>
      </View>
    );
  }

  if (error) {
    return (
      <View style={styles.centered}>
        <Text style={styles.errorText}>{error}</Text>
        <Button title="重试" onPress={fetchScenes} />
      </View>
    );
  }
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
    <View style={{ flex: 1 }}>
      <ParallaxScrollView
        headerImage={
          <Image
            source={require('../../assets/images/familyBackground.png')} // 替换成你的头图背景
            style={styles.headerImage}
          />
        }
        headerBackgroundColor={{ dark: '#222', light: '#fff' }}
      >
        {/* <Stack.Screen options={{ headerShown: false }} /> */}
        <View style={styles.contentContainer}>
          <Text style={styles.headerText}>场景列表</Text>
          <FlatList
            data={scenes}
            scrollEnabled={false}
            renderItem={({ item }) => (
              <Scene
                sceneName={item.name}
                priority={item.priority}
                onIncrease={() => handlePriorityChange(item.id, 'increase')}
                onDecrease={() => handlePriorityChange(item.id, 'decrease')}
                onDelete={() => handleDeleteScene(item.id)} // 传递删除逻辑
                onEdit={() => handleEditScene(item.id, item.name)}
              />
            )}
            keyExtractor={item => item.id.toString()}
            ListEmptyComponent={
              <View style={styles.centered}>
                <Text>暂无场景数据。</Text>
              </View>
            }
          />
        </View>
      </ParallaxScrollView>

      <TouchableOpacity
        style={{
          position: 'absolute',
          right: 40,
          bottom: 80,
          width: 55,
          height: 55,
          borderRadius: 30,
          backgroundColor: '#fff',
          borderWidth: 1,
          justifyContent: 'center',
          alignItems: 'center',
          borderColor: '#eee',
          shadowColor: '#000',
          shadowOffset: { width: 0, height: 2 },
          shadowOpacity: 0.2,
          shadowRadius: 3,
          zIndex: 200,
          overflow: 'visible',
        }}
        onPress={async () => {
          try {
            await createScene({
              name: `新场景${Date.now()}`,
              description: '自动创建',
              enabled: true,
            });
            fetchScenes(); // 创建后刷新列表
          } catch (err) {
            Alert.alert('错误', '创建场景失败');
          }
        }}
      >
        <FontAwesome name="plus-circle" size={50} color="#888" />
      </TouchableOpacity>
    </View>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  headerImage: {
    width: '100%',
    height: '100%',
  },
  contentContainer: {
    padding: 0,
    width: '100%',
  },
  headerText: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 10,
  },
  centered: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    minHeight: 200, // 确保加载或错误状态有足够空间显示
  },
  errorText: {
    color: 'red',
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 10,
  },
});